<!--
 * @Description:: 请补充填写
 * @Version: 1.0
 * @Author: smallWhite
 * @Date: 2024-08-24 15:55:52
 * @LastEditors: smallWhite
 * @LastEditTime: 2024-08-27 20:34:01
 * @FilePath: /aichatadmin/src/components/scoket/index.vue
-->
<template>
  <div>
    <button
      @click="connectMsg">连接设备</button>
    <button
      @click="closeWs">断开设备</button>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, defineComponent } from 'vue'

import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { HTTP_URL } from '@/api/api'
const store = useStore()
const userId = ref('')
let emit = defineEmits(['onMessage'])
onMounted(() => {
  userId.value = localStorage.getItem('userId') || ''
  if (userId.value) {
    connectMsg()
  } else {
    store.dispatch('disconnect')
  }
})

//连接设备  （具体路径和后端规定）
function connectMsg() {
  console.log('连接设备')
  const toIp = `${HTTP_URL.WSSURL}/webSocket/${userId.value}`
  store.dispatch('connect')
  initWebSocket(toIp)
}
// 设备断开
function closeWs() {
  closeWebSocket()
  store.dispatch('disconnect')
}

let array: any[] = []
let websocket: WebSocket | null = null // 用于存储实例化后websocket
let rec: any // 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
var content: any = ''
// 创建websocket
function creatWebSocket(wsUrl: string) {
  console.log('websocket==================')
  // 判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    console.log('当前浏览器支持 WebSocket')
  } else if ('MozWebSocket' in window) {
    console.log('当前浏览器支持 MozWebSocket')
  } else {
    console.log('当前浏览器不支持 WebSocket')
  }
  try {
    initWebSocket(wsUrl) // 初始化websocket连接
  } catch (e) {
    console.log('尝试创建连接失败')
    reConnect(wsUrl) // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
}
// 初始化websocket
function initWebSocket(wsUrl: string) {
  websocket = new WebSocket(wsUrl)
  console.log('websocket:', websocket)
  websocket.onopen = function () {
    console.log('WebSocket连接成功')
    websocketOpen()
  }
  //   // 接收
  websocket.onmessage = function (e: MessageEvent<any>) {
    websocketonmessage(e)
  }
  // 连接发生错误
  websocket.onerror = function () {
    console.log('WebSocket连接发生错误')
    //     isConnect = false; // 连接断开修改标识
    reConnect(wsUrl) // 连接错误 需要重连
  }
  websocket.onclose = function (e) {
    websocketclose(e)
  }
}
// 定义重连函数
let reConnect = (wsUrl: string) => {
  console.log('尝试重新连接')
  if (store.state.isConnected) return // 如果已经连上就不在重连了
  rec && clearTimeout(rec)
  rec = setTimeout(function () {
    // 延迟5秒重连  避免过多次过频繁请求重连
    creatWebSocket(wsUrl)
  }, 5000)
}
// 创建连接
function websocketOpen() {
  console.log('连接成功')
  store.dispatch('connect') // 修改连接状态
}
// 数据接收
function websocketonmessage(e: MessageEvent<any>) {
  emit('onMessage', e.data)
}
// 关闭
function websocketclose(e: any) {
  console.log(e)
  store.dispatch('disconnect') // 修改连接状态
  console.log('connection closed (' + e.code + ')')
}
// 数据发送
function websocketsend(data: any) {
  console.log('发送的数据', data, JSON.stringify(data))
  if (websocket && store.state.isConnected) {
    // 检查连接状态
    websocket.send(JSON.stringify(data))
  } else {
    ElMessage({
      showClose: true,
      message: '请选择设备连接',
      type: 'error'
    })
  }
}
// 实际调用的方法==============
// 发送
function sendWebSocket(data: any) {
  // 如果未保持连接状态 不允许直接发送消息 提示请选择连接设备
  if (!store.state.isConnected) {
    ElMessage({
      showClose: true,
      message: '请选择设备连接',
      type: 'error'
    })
  } else {
    websocketsend(data)
    console.log('------------------')
  }
}
// 关闭
let closeWebSocket = () => {
  if (websocket) {
    websocket.close()
    ElMessage({
      showClose: true,
      message: '设备已关闭',
      type: 'success'
    })
  }
}
</script>